package com.baidu.videoseries.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.baidu.videoseries.R;
import com.baidu.videoseries.adapter.AudioAdapter;
import com.baidu.videoseries.bean.MediaBean;
import com.baidu.videoseries.constant.Config;
import com.baidu.videoseries.receiver.ResponseReceiver;
import com.baidu.videoseries.service.MusicService;
import com.baidu.videoseries.util.AnimHelper;
import com.baidu.videoseries.util.MediaUtil;
import com.kvin.toolkit.receiver.OnReceiveListener;
import com.kvin.toolkit.utils.StringUtils;
import com.kvin.toolkit.utils.system.SystemUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class AudioFragment extends BaseFragment implements AudioAdapter.OnItemClickListener {

    @BindView(R.id.m_list)
    RecyclerView mList;
    @BindView(R.id.previous_iv)
    ImageView previousIv;
    @BindView(R.id.play_iv)
    ImageView playIv;
    @BindView(R.id.next_iv)
    ImageView nextIv;
    Unbinder unbinder;

    private ArrayList<MediaBean> mData;
    private AudioAdapter mAdapter;
    private ResponseReceiver mReceiver;

    private AnimHelper mAnimHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_audio, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void init() {
        this.mAnimHelper = AnimHelper.getInstance();
        this.mReceiver = new ResponseReceiver();
        getActivity().registerReceiver(mReceiver, new IntentFilter(Config.MediaAction.ACTION_RESPONSE));
        this.mReceiver.setOnReceiveListener(mStatusListener);
        this.previousIv.setOnClickListener(this);
        this.playIv.setOnClickListener(this);
        this.nextIv.setOnClickListener(this);

        mData = new ArrayList<>();
        mAdapter = new AudioAdapter(mData, getActivity());
        this.mList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        this.mList.setAdapter(mAdapter);
        this.mAdapter.setOnItemClickListener(this);

        loadingData(0);

    }


    @Override
    public void loadingData(int pageNum) {
        LoaderManager mManager = getActivity().getSupportLoaderManager();
        mManager.initLoader(0, null, new AudioLoaderCallback());
    }

    @Override
    public void onClick(View v) {
        this.mAnimHelper.startAnim(v, 1000);
        if (v == playIv) {
            sendCommand(playIv.isSelected() ? Config.Command.PLAY : Config.Command.PAUSE, -1);
        } else if (v == nextIv) {
            sendCommand(Config.Command.NEXT, -1);
        } else if (v == previousIv) {
            sendCommand(Config.Command.PREVIOUS, -1);
        }
    }


    /**
     * send command
     *
     * @param command
     */
    private void sendCommand(int command, int index) {
        this.sendCommand(command, index, null, null);

    }

    private void sendCommand(int command, int index, ArrayList<MediaBean> list, MediaBean file) {
        mIntent = new Intent(Config.MediaAction.ACTION_COMMAND);
        if (list != null) mIntent.putParcelableArrayListExtra(Config.Key.FILE_LIST, list);
        if (file != null) mIntent.putExtra(Config.Key.FILE, file);
        mIntent.putExtra(Config.Key.COMMAND, command);
        mIntent.putExtra(Config.Key.CURSOR_INDEX, index);
        getActivity().sendBroadcast(mIntent);
    }


    @Override
    public void onItemClick(int position) {
        launchServer();
        sendCommand(Config.Command.CURSOR_INDEX, position);
    }

    /**
     * launch server
     */
    private void launchServer() {
        if (!SystemUtils.isServiceWork(getActivity(), MusicService.class.getSimpleName())) {
            mIntent = new Intent(getActivity(), MusicService.class);
            mIntent.setAction(Config.MediaAction.ACTION_AUDIO_PLAYER);
            getActivity().startService(mIntent);
        }
    }


    /**
     * on player status listener
     */
    private OnReceiveListener mStatusListener = new OnReceiveListener() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) return;
            int response = intent.getIntExtra(Config.Key.STATUS, -1);
            switch (response) {
//                case Config.Status.RES_DATA:
//                    ArrayList<MediaBean> temp = intent.getParcelableArrayListExtra(Config.Key.FILE_LIST);
//                    if (temp != null) mData.addAll(temp);
//                    mAdapter.notifyDataSetChanged();
//                    break;
                case Config.Status.PLAYING:
                    playIv.setSelected(true);
                    break;
                case Config.Status.PAUSE:
                    playIv.setSelected(false);
                    break;

            }
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiver);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    /**
     * audio ck
     */
    class AudioLoaderCallback implements LoaderManager.LoaderCallbacks<Cursor> {
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//            LogUtils.v(TAG, "-----onCreateLoader-----");
            CursorLoader loader = null;
            Uri url = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            String[] projection = MediaUtil.EXTERNAL_COLUMNS;
            String sort = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
            if (id == 0) {
                loader = new CursorLoader(getActivity(), url, projection, null, null, sort);
            }
            return loader;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//            LogUtils.v(TAG, "-----onLoadFinished-----");
            if (data == null) return;
            ArrayList<MediaBean> temp = new ArrayList<>();
            MediaBean bean = null;
            while (data.moveToNext()) {
                String name = data.getString(data.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String artist = data.getString(data.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String album = data.getString(data.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                long duration = data.getLong(data.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String url = data.getString(data.getColumnIndex(MediaStore.Audio.Media.DATA));
//                int isMusic = data.getInt(data.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
                bean = new MediaBean();
                bean.setStoryName(name);
                bean.setAuthor(artist);
                bean.setDuration(StringUtils.parseTime((int) duration));
                bean.setTargetUrl(url);
                bean.setAlbumName(album);
                temp.add(bean);
//                LogUtils.v(TAG, "name=" + name + ":artist=" + artist + ":album=" + album + ":duration=" + StringUtils.parseTime((int) duration)+":isMusic="+isMusic);
            }
            sendCommand(Config.Command.DATA_CHANGED, -1, temp, null);
            mData.addAll(temp);
            mAdapter.notifyDataSetChanged();
            data.close();
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
//            LogUtils.v(TAG, "-----onLoaderReset-----");
            mData.clear();
        }
    }


}
